package util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URISyntaxException;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.client.ClientHttpRequest;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.http.client.SimpleClientHttpRequestFactory;

import com.alibaba.fastjson.JSON;

import model.JsonVO;

public class HttpUtil {
	 public final static String HOST = "";
	/* public final static String HOST = "http://jm.changji.com/v2";*/
//	public final static String HOST = "http://127.0.0.1:8081/v2";

	public static JsonVO HttpRequest(String path, HttpMethod method, String headerParams, String bodyParams) {
		String re = "";
		try {
			URI uri = new URI(HOST + path);
			SimpleClientHttpRequestFactory schr = new SimpleClientHttpRequestFactory();
			
			if (bodyParams != null && !"".equals(bodyParams) && HttpMethod.GET.equals(method)) {
				uri = new URI(uri.toString()+"?"+bodyParams);
			}
			
			ClientHttpRequest chr = schr.createRequest(uri, method);

			HttpHeaders headers = chr.getHeaders();
			if (headerParams != null && !"".equals(headerParams)) {
				System.out.println(headerParams);
				String[] pList = headerParams.split("&");
				for (String p : pList) {
					String[] entry = p.split("=");
					if(entry.length==1){
						headers.set(entry[0], "");
					}else{
						headers.set(entry[0], entry[1]);
					}
				}
			}
			
			if (bodyParams != null && !"".equals(bodyParams) && HttpMethod.POST.equals(method)) {
				chr.getBody().write(bodyParams.getBytes());// body中设置请求参数
			}
			ClientHttpResponse res = chr.execute();
			InputStream is = res.getBody(); // 获得返回数据,注意这里是个流
			InputStreamReader isr = new InputStreamReader(is);
			BufferedReader br = new BufferedReader(isr);
			String str = "";
			while ((str = br.readLine()) != null) {
				re += str;
			}
			System.out.println(re);// 获得页面内容或返回内容
		} catch (URISyntaxException e1) {
			e1.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		if ("".equals(re)) {
			return  null;
		}else{
			return JSON.parseObject(re, JsonVO.class);
		}
	}

	public static void main(String[] args) {
//		 HttpUtil.HttpRequest("/login/sendSms", HttpMethod.GET, "SECRET=11&AUTHORIZATION=df9f89b5d1672846330035d95838c118","type=1");

//		String re = HttpUtil.HttpRequest("/address/addAddress", HttpMethod.POST,
//				"SECRET=11&AUTHORIZATION=df9f89b5d1672846330035d95838c118", "name=12&age=10");
//		System.out.println(re);
	}
}
